package com.fyl.core.utils;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public final class ZipFileUtil {


    public static String compressFolder(String path) {
        String zipPath = path + ".zip";
        try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath));
             BufferedOutputStream bos = new BufferedOutputStream(out)) {
            File sourceFile = new File(path);
            String base = sourceFile.getName();
            compress(out, bos, sourceFile, base);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return zipPath;
    }

    private static void compress(ZipOutputStream out, BufferedOutputStream bos, File sourceFile, String base) throws Exception {
        if (sourceFile.isDirectory()) {
            File[] flist = sourceFile.listFiles();
            if (flist.length == 0) {
                out.putNextEntry(new ZipEntry(base + "/"));
            } else {
                for (int i = 0; i < flist.length; i++) {
                    compress(out, bos, flist[i], base + "/" + flist[i].getName());
                }
            }
        } else {
            ZipEntry zipEntry = new ZipEntry(base);
            zipEntry.setSize(sourceFile.length());
            zipEntry.setTime(sourceFile.lastModified());
            out.putNextEntry(zipEntry);

            InputStream inputStream = new BufferedInputStream(new FileInputStream(sourceFile));
            int readLength = 0;
            byte[] buffer = new byte[512];
            while ((readLength = inputStream.read(buffer, 0, 512)) != -1) {
                out.write(buffer, 0, readLength);
            }
            inputStream.close();
        }
    }

}
